package com.iagent.resovler.result;

import com.iagent.annotation.Order;
import com.iagent.constant.HttpConstant;
import com.iagent.exception.NotFoundResultResolverException;
import com.iagent.factory.IagentConfiguration;
import com.iagent.util.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @auther liujieyu
 * @date 2022/12/2
 * @description 文件流结果解析器
 * @since 2.2.0
 */
@Order(HttpConstant.MAX_ORDER / 2)
public class BinaryResultResolver extends AbstractResultResolver {

    /**
     * 当前仅支持File、byte数组以及InputStream流对象
     */
    @Override
    public boolean isResolver(Class<?> returnClass) {
        return File.class.isAssignableFrom(returnClass) ||
                byte[].class.isAssignableFrom(returnClass) ||
                InputStream.class.isAssignableFrom(returnClass);
    }

    @Override
    public Object resolver(byte[] data, Class<?> returnClass) throws Throwable {
        if (byte[].class.isAssignableFrom(returnClass)) {
            return data;
        } else if (File.class.isAssignableFrom(returnClass)) {
            return IOUtils.writeToFileByBytes(getCacheTmpFilePath(), data);
        } else if (InputStream.class.isAssignableFrom(returnClass)) {
            File tempFile = IOUtils.writeToFileByBytes(getCacheTmpFilePath(), data);
            return new FileInputStream(tempFile);
        } else {
            throw new NotFoundResultResolverException("Not Found Result Resolver");
        }
    }
}
